package com.kgc.sbt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.sbt.api.BuyLimitApi;
import com.kgc.sbt.config.BuyLimitConfig;
import com.kgc.sbt.api.GoodsApi;
import com.kgc.sbt.api.GoodsNoticeApi;
import com.kgc.sbt.domain.LimitBuy;
import com.kgc.sbt.util.RedisUtils;
import com.kgc.sbt.util.RequestResult;
import com.kgc.sbt.util.ResultBuildUtil;
import com.kgc.sbt.util.SendSmsUtil;
import io.swagger.annotations.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/**
 * Created on 2021/6/21.
 * <p>
 * Author: GongMingJie
 * <p>
 * Description: 管理员业务入口
 */
@Slf4j
@RestController
@Api(tags = "管理员操作接口，版本号:1.0.0")
public class AdminController {

    @Reference
    private BuyLimitApi buyLimitApi;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private BuyLimitConfig buyLimitConfig;

    @Reference
    private GoodsNoticeApi goodsNoticeApi;

    @Reference
    private GoodsApi goodsApi;

    /**
     * Created on 2021/6/21
     * Author: GongMingJie
     * @param
     * @return Description: 管理员发布抢购活动
     */
    @PostMapping("/postBuyLimit")
    @ApiOperation(value = "管理员发布抢购活动", notes = "必传商品编号、活动开始时间，结束时间")
    @ApiResponses({
            @ApiResponse(code = 9999,message = "创建抢购活动失败"),
            @ApiResponse(code = 9998,message = "传入数据不完整"),
            @ApiResponse(code = 9997,message = "此商品不存在"),
            @ApiResponse(code = 9996,message = "库存为0，无法发布抢购活动"),
            @ApiResponse(code = 9995,message = "商品已经下架，无法发布抢购活动"),
            @ApiResponse(code = 0000,message = "创建抢购活动成功"),
    })
    public RequestResult<String> postBuyLimit(LimitBuy limitBuy) {
        // 判断是否选择商品和设置开始时间以及结束时间
        log.info("------ 从前台获取的抢购活动：{}", limitBuy);

        if (limitBuy.getGoodsId() != null && limitBuy.getStartTime() != null && limitBuy.getEndTime() != null && limitBuy.getPrice() != null) {
            // 判断抢购活动商品是否存在
            if (goodsApi.queryGoodsById(limitBuy.getGoodsId()) != null){

                if (goodsApi.queryGoodsById(limitBuy.getGoodsId()).getStock() == 0){
                    return ResultBuildUtil.fail("9996","库存为0，无法发布抢购活动");
                }

                if (goodsApi.queryGoodsById(limitBuy.getGoodsId()).getStatus() == 0){
                    return ResultBuildUtil.fail("9995","商品已经下架，无法发布抢购活动");
                }

                // 存在
                // 调用抢购活动模块，将数据入库
                LimitBuy limitBuy1 = buyLimitApi.createBuyLimit(limitBuy);
                if (limitBuy1 != null) {
                    log.info("------ 创建抢购活动成功，抢购活动为:{}", limitBuy1);
                    // 将此抢购活动存入redis,设置失效时长为开始时间-当前时间
                    redisUtils.set("buyLimitIdFlag" + limitBuy1.getId(),0);
                    redisUtils.lSet("buyLimitIds",limitBuy1.getId());
                    redisUtils.lock("buyLimitStart-60" + limitBuy1.getId(), null, (limitBuy1.getStartTime().getTime() - System.currentTimeMillis()) / 1000 - 60);
                    redisUtils.lock("buyLimitStart" + limitBuy1.getId(), null, (limitBuy1.getStartTime().getTime() - System.currentTimeMillis()) / 1000);
                    redisUtils.lock("buyLimitEnd" + limitBuy1.getId(), null, (limitBuy1.getEndTime().getTime() - System.currentTimeMillis()) / 1000);

                    return ResultBuildUtil.success("创建抢购活动成功");
                } else {
                    return ResultBuildUtil.fail("9999", "创建抢购活动失败");
                }
            }else {
                return ResultBuildUtil.fail("9997", "此商品不存在");
            }
        } else {
            return ResultBuildUtil.fail("9998", "传入数据不完整");
        }
    }


    /**
     * Created with IntelliJ IDEA.
     *
     * @Author: tianzw
     * @Description: 管理员下架上架商品
     */
    @PostMapping("/putGoods")
    @ApiOperation(value = "上架商品", notes = "管理员通过id上架商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, value = "商品id")
    })
    public RequestResult<String> putGoods(@RequestParam Integer id) {

        // 判断有无此商品
        if (goodsApi.queryGoodsById(id) == null){
            return ResultBuildUtil.fail("8003","没有此商品");
        }

        if (goodsApi.putGoodsById(id)) {
            return ResultBuildUtil.success("上架成功");
        }
        return ResultBuildUtil.fail("9002", "商品已上架，无需再次上架");
    }

    @PostMapping("/pullGoods")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, value = "商品id")
    })
    @ApiOperation(value = "下架商品", notes = "管理员通过id下架商品")
    public RequestResult<String> pullGoods(@RequestParam Integer id) {

        // 判断有无此商品
        if (goodsApi.queryGoodsById(id) == null){
            return ResultBuildUtil.fail("8003","没有此商品");
        }

        if (goodsApi.pullGoodsById(id)) {
            return ResultBuildUtil.success("下架成功");
        }
        return ResultBuildUtil.fail("9002", "商品已下架，无需再次下架");
    }

    /**
     * Created with IntelliJ IDEA.
     *
     * @Author: tianzw
     * @Description: 增加库存
     */
    @PostMapping("/putStock")
    @ApiOperation(value = "增加库存", notes = "需要传入 商品id，增加的商品数量")

    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, value = "商品id"),
            @ApiImplicitParam(name = "stockNumber", required = true, value = "增加库存的数量")
    })
    public RequestResult<String> putStock(@RequestParam Integer id, @RequestParam Integer stockNumber) {

        // 判断有无此商品
        if (goodsApi.queryGoodsById(id) == null){
            return ResultBuildUtil.fail("8003","没有此商品");
        }

        if (goodsApi.queryGoodsById(id).getStatus()==0){
            return ResultBuildUtil.fail("8001","商品未上架不能更改库存");
        }
        if (stockNumber<0){
            return ResultBuildUtil.fail("8002","增加库存的数量不能小于0");
        }
        if (goodsApi.putStockById(id, stockNumber)) {

            //通过商品id查询 到货通知表 用户id
            List<Integer> userIds = goodsNoticeApi.queryUserIdByGoodsId(id);
            log.info("----{}", userIds);

            if(userIds.size()>0){
                //通过用户id查询电话号码

                for(Integer userId:userIds){
                    String phoneNo=goodsNoticeApi.queryPhoneNoByUserId(userId);
                    SendSmsUtil.sendSms(phoneNo,"6666");
                    goodsNoticeApi.deleteNoticeByUserIdAndGoodsId(userId,id);
                }
                return ResultBuildUtil.success("库存增加成功,上货通知已经发送给预约用户");
            }
            return ResultBuildUtil.success("库存增加成功");
        }
        return ResultBuildUtil.fail("9002", "库存未增加成功");
    }

    /**
     * @param id
     * @param stockNumber
     * @return 减少库存
     */
    @PostMapping("/puLLStock")
    @ApiOperation(value = "减少库存", notes = "需要传入 商品id，增加的商品数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, value = "商品id"),
            @ApiImplicitParam(name = "stockNumber", required = true, value = "减少库存的数量")
    })
    public RequestResult<String> pullStock(@RequestParam Integer id, @RequestParam Integer stockNumber) {

        // 判断有无此商品
        if (goodsApi.queryGoodsById(id) == null){
            return ResultBuildUtil.fail("8003","没有此商品");
        }

        if (goodsApi.queryGoodsById(id).getStatus()==0){
            return ResultBuildUtil.fail("8004","商品未上架不能更改库存");
        }
        if (stockNumber<0){
            return ResultBuildUtil.fail("8005","减少库存的数量不能小于0");
        }
        if (goodsApi.pullStockById(id, stockNumber)) {
            return ResultBuildUtil.success("库存删除成功");
        }
        return ResultBuildUtil.success("输入减少库存的数量不能大于库存的值，库存最多减少为0，当前库存为0");
    }



}
